/*
CpGears v1.0

Copyright (c) 2010 Yves Riel http://www.flash-factor.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package cpgears.helpers {
	
	import cpgears.log.ILogger;
	import cpgears.log.LogManager;
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.external.ExternalInterface;
	import flash.utils.describeType;
	
	/**
	 * Helper class to manipulate Captivate Data
	 * 
	 * @author Whyves
	 */
	public class CaptivateHelper{
		
		private static const mLogger:ILogger = LogManager.getLogger("cpgears.helpers.CaptivateHelper");
		
		/**
		 * Creates an object containing the widget properties.
		 * 
		 * @param	xml An XML object describing the widget properties and their associated values.
		 * @return An object matching the properties described in the XML.
		 */
		public static function createObjectFromXmlData(xml:XML):Object
		{
			var returnObj:Object = new Object();

			for (var i:int = 0; i < XMLList(xml.property).length(); i++) {
				
				var propName:String = xml.property[i].@id;
				var dataType:String = xml.property[i].child(0).name();
				var thisProperty:XMLList = XMLList(xml.property[i]);

				switch (dataType) {
					
					case "number" :
					returnObj[propName] = translateNumber(thisProperty,true);
					break;
					
					case "string" :
					returnObj[propName] = translateString(thisProperty, true);
					break;
					
					case "array" :
					returnObj[propName] = translateArray(thisProperty.child(0));
					break;
					
					case "object" :
					for each (var property:XML in thisProperty.children()) {
						returnObj[propName] = createObjectFromXmlData(property);
						break;
					}
					break;
					
					case "true" :
					returnObj[propName] = true;
					break;
					
					case "false" :
					returnObj[propName] = false;
					break;
					
					case "null" :
					returnObj[propName] = null;
					break;
					
					default :
					returnObj[propName] = ifAllElseFails(thisProperty, true);
					break;
				}
			}
			
			return returnObj;
		}
		
		static private function translateString(xml:XMLList, fromObject:Boolean):String
		{
			if (fromObject) {
				return String(xml.child(0).child(0));
			} else {
				return String(xml.child(0));
			}
		}
		
		private static function translateArray(xml:XMLList):Array
		{
			var returnArray:Array = new Array();
			
			for (var i:int = 0; i < XMLList(xml.property).length(); i++) {
				
				var dataType:String = xml.property[i].child(0).name();
				var thisProperty:XMLList = XMLList(xml.property[i]);
				
				switch (dataType) {
					
					case "number" :
					returnArray.push(translateNumber(thisProperty,false));
					break;
					
					case "string" :
					returnArray.push(translateString(thisProperty, false));
					break;
					
					case "array" :
					returnArray.push(translateArray(thisProperty.child(0)));
					break;
					
					case "object" :
					for each (var property:XML in thisProperty.children()) {
						returnArray.push(createObjectFromXmlData(property));
					}
					break;
					
					case "true" :
					returnArray.push(true);
					break;
					
					case "false" :
					returnArray.push(false);
					break;
					
					case "null" :
					returnArray.push(null);
					break;
					
					default :
					returnArray.push(ifAllElseFails(thisProperty, false));
					break;
					
				}
				
			}
			
			return returnArray;
		}
		
		private static function translateNumber(xml:XMLList, fromObject:Boolean):Number
		{
			if (fromObject) { // So an object is going to store this value
				return Number(xml.child(0).child(0));
			} else { // An Array is going to store this value
				return Number(xml.child(0));
			}
		}
		
		private static function ifAllElseFails(xml:XMLList, fromObject:Boolean):XMLList // Could return a string or an XMLList
		{
			if (fromObject) {
				return xml.child(0).child(0);
			} else {
				return xml.child(0);
			}
		}
		
		
		/**
		 * Adds an external interface in a safely manner.
		 * 
		 * <P>Catches any exception and logs it.</P>
		 * 
		 * @param	methodName The name of the method to attach to.
		 * @param	methodClosure The method closure (function) that will get called.
		 * @return <code>true</code> if successfully attached, <code>false</code> otherwise.
		 */
		public static function addExternalInterface(methodName:String, methodClosure:Function):Boolean {
			var succes:Boolean = false;
			var logger:ILogger = LogManager.getLogger("cpgears.helpers.CaptivateHelper");
			try {
				ExternalInterface.addCallback(methodName, methodClosure);
				succes = true;
			} catch (err:Error){
				logger.error("Could not add external interface for method '{0}'", methodName);
			}
			return succes
		}
	}
}